package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.model.result.Result;
import com.xuecheng.content.service.TeachpanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeachpanServiceImpl implements TeachpanService {

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {

        List<TeachplanDto> teachplanDtos = teachplanMapper.selectTreeNodes(courseId);

        return teachplanDtos;
    }



    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        //通过是否有课程ID来判断为修改还是更新
        Long teachplanId=saveTeachplanDto.getId();
        if (teachplanId==null){
            //新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            
            //确认排序字段，找到他的同级节点的个数，排序字段就是个数加一，
            Long parentid = saveTeachplanDto.getParentid();
            Long courseId = saveTeachplanDto.getCourseId();
            Integer count = getCount(courseId, parentid);
            //排序字段为个数+1
            teachplan.setOrderby(count+1);


            teachplanMapper.insert(teachplan);

        }else {
            //修改
            Teachplan teachplan = teachplanMapper.selectById(teachplanId);
            //将参数复制
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }

    }

    
    @Override
    public Result deleteTeachplan(Long id) {
        //判断课程计划是否为空
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan==null){
           return Result.fail("120409","课程计划信息还有子级信息，无法操作");
        }

        Integer grade = teachplan.getGrade();
        if (grade==1){
            //判断该节点下是否有子节点 因为一级标题章需要将章下的所有小节都删除以后才能删除
            LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
            //构建条件
            queryWrapper.eq(Teachplan::getCourseId,teachplan.getCourseId()).eq(Teachplan::getParentid,id);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            //判断
            if (teachplans!=null&&teachplans.size()>0){
                return Result.fail("120409","课程计划信息还有子级信息，无法操作");
            }

            int i = teachplanMapper.deleteById(id);
            //判断是否删除成功
            if (i<=0){
                return Result.fail("120409","删除失败");
            }else {
                return Result.success();
            }

        }else {
            int i = teachplanMapper.deleteById(id);
            if (i<=0){
                return Result.fail("120409","删除失败");
            }else {
                return Result.success();
            }
        }
    }

    @Override
    public void moveNode(String type, Long id) {
        if (type.equals("moveup")){
            //获取课程计划
            Teachplan teachplan = teachplanMapper.selectById(id);
            //获取排序字段
            Integer orderby = teachplan.getOrderby();
            if (orderby==1){
                XueChengPlusException.cast("已经是第一节了");
            }
            //根据课程id,父节点ID。排序字段查询
            Teachplan teachplan1 = teachplanMapper.selectOne(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId, teachplan.getCourseId()).eq(Teachplan::getOrderby, orderby-1).eq(Teachplan::getParentid, teachplan.getParentid()));
            teachplan.setOrderby(orderby-1);
            teachplan1.setOrderby(orderby);
            int i = teachplanMapper.updateById(teachplan);
            int i1 = teachplanMapper.updateById(teachplan1);
            if (i<=0||i1<=0){
                XueChengPlusException.cast("移动失败");
            }
        }else if (type.equals("movedown")){
            //获取课程计划
            Teachplan teachplan = teachplanMapper.selectById(id);
            //获取排序字段
            Integer orderby = teachplan.getOrderby();
            Long courseId = teachplan.getCourseId();
            Long parentid = teachplan.getParentid();

            LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentid).orderByAsc(Teachplan::getOrderby);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);

            //判断是不是最后一节
            if (teachplan.getId()==teachplans.get(teachplans.size()-1).getId()){
                XueChengPlusException.cast("已经是最后一节了");
            }

            //在集合中取出下一节课程计划
            Teachplan teachplan1 = teachplans.get(orderby);

            //修改课程计划
            teachplan.setOrderby(orderby+1);
            teachplan1.setOrderby(orderby);

            int i = teachplanMapper.updateById(teachplan);
            int i1 = teachplanMapper.updateById(teachplan1);

            if (i<=0||i1<=0){
                XueChengPlusException.cast("移动失败");
            }

        }else {
            XueChengPlusException.cast("参数非法");
        }
    }



    @Override
    @Transactional
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
       //课程计划
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();

        Teachplan teachplan = teachplanMapper.selectById(teachplanId);

        if (teachplan==null){
            XueChengPlusException.cast("课程计划不存在");
        }

        if (teachplan.getGrade()!=2){
            XueChengPlusException.cast("课程计划非法，只允许二级课程计划绑定媒资文件");
        }


        //先删除原有记录，根据课程计划ID，删除它所绑定的媒资
        int i = teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, bindTeachplanMediaDto.getTeachplanId()));


        //再添加新纪录
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachplanMediaDto,teachplanMedia);
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());

        int insert = teachplanMediaMapper.insert(teachplanMedia);

        return teachplanMedia;

    }



    private Integer getCount(Long courseId, Long parentid) {
        LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentid);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }


}
